package com.pay.ioopos;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager.NetworkCallback;
import android.net.Network;
import android.net.NetworkRequest;
import android.util.Log;

import androidx.annotation.NonNull;

import com.pay.ioopos.activity.AbstractActivity;
import com.pay.ioopos.sqlite.SettingHelper;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TransKeyLoader {
    private static final String TAG = TransKeyLoader.class.getSimpleName();
    private static TransKeyLoader loader = new TransKeyLoader();

    private TransKeyLoader() {

    }

    public static TransKeyLoader getInstance() {
        return loader;
    }

    public void load(Activity activity) {
        DataStore store = DataFactory.getDataStore();
        if (!store.getTransKey().equals(SettingHelper.INIT_KEY)) {
            return;
        }
        ((AbstractActivity)activity).showToast("设备未配置，自动获取参数...");
        ConnectivityManager manager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCallback callback = new NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                DataStore store = DataFactory.getDataStore();
                if (!store.getTransKey().equals(SettingHelper.INIT_KEY)) {
                    return;
                }
                NetworkCallback callback = this;
                startLoad(activity, new LoadCallback() {
                    @Override
                    public void onSuccess(String transKey) {
                        store.setTransKey(transKey);
                        manager.unregisterNetworkCallback(callback);
                    }

                    @Override
                    public void onFail(String msg) {
                        ((AbstractActivity)activity).showToast("参数获取失败：" + msg);
                    }

                    @Override
                    public void onError(Exception e) {
                        Log.e(TAG, "密钥获取异常: ", e);
                        ((AbstractActivity)activity).showToast("参数获取失败：" + e.getMessage());
                    }
                });

            }

            @Override
            public void onLost(@NonNull Network network) {
                super.onLost(network);
            }
        };
        manager.registerNetworkCallback(new NetworkRequest.Builder().build(), callback);
    }

    private interface LoadCallback {
        void onSuccess(String transKey);
        void onFail(String msg);
        void onError(Exception e);
    }

    private void startLoad(Activity activity, LoadCallback callback) {
        try {
            load(activity, callback);
        } catch(Exception e) {
            callback.onError(e);
        }
    }

    private void load(Activity activity, LoadCallback callback) throws Exception {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String sn = DeviceUtils.sn(activity);
        String key = DataFactory.getDataStore().getTransKey();
        String serverUrl = DataFactory.getDataStore().getServerUrl();
        String sign = Utils.sha256(sn + timestamp + key);
        JSONObject json = new JSONObject();
        json.put("version", "v2");
        json.put("deviceSn", sn);
        json.put("brand", "ioopos");
        json.put("timestamp", timestamp);
        json.put("sign", sign);
        String jsonString = json.toString();
        jsonString = HttpUtil.post(serverUrl + "/qrpos/api/mch/device/getkey", jsonString);
        json = new JSONObject(jsonString);
        String status = json.getString("status");
        if (!status.equals("200")) {
            callback.onFail("["+ status +"]" + json.getString("message"));
            return;
        }
        JSONObject result = json.getJSONObject("result");
        String keyStatus = result.getString("status");
        switch (keyStatus) {
            case "NOCHANGE":
                callback.onFail("设备密钥丢失，请重置密钥");
                break;
            case "SUCCESS":
                callback.onSuccess(result.getString("deviceKey"));
                loaded(activity, callback);
                break;
            case "NOFOUND":
                callback.onFail("设备未添加到后台");
                break;
            default:
                callback.onFail("["+ keyStatus +"]" + result.getString("errMsg"));
                break;
        }
    }

    private void loaded(Activity activity, LoadCallback callback) throws Exception {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String sn = DeviceUtils.sn(activity);
        String key = DataFactory.getDataStore().getTransKey();
        String serverUrl = DataFactory.getDataStore().getServerUrl();
        String sign = Utils.sha256(sn + timestamp + key);
        JSONObject json = new JSONObject();
        json.put("version", "v2");
        json.put("deviceSn", sn);
        json.put("brand", "ioopos");
        json.put("timestamp", timestamp);
        json.put("sign", sign);
        String jsonString = json.toString();
        jsonString = HttpUtil.post(serverUrl + "/qrpos/api/mch/device/up", jsonString);
        json = new JSONObject(jsonString);
        String status = json.getString("status");
        if (!status.equals("200")) {
            callback.onFail("["+ status +"]" + json.getString("message"));
            return;
        }
        JSONObject result = json.getJSONObject("result");
        String keyStatus = result.getString("status");
        if (!keyStatus.equals("SUCCESS")) {
            callback.onFail("["+ keyStatus +"]" + json.getString("errMsg"));
            return;
        }
    }

}
